// ==UserScript==
// @name         拼多多收藏夹采集器
// @namespace    http://tampermonkey.net/
// @version      1.0.0
// @description  自动采集拼多多收藏夹商品数据，支持首页及翻页数据采集
// @author       楚子风
// @match        https://mobile.yangkeduo.com/likes.html*
// @grant        GM_xmlhttpRequest
// @grant        GM_download
// @grant        unsafeWindow
// @require      https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js
// @scriptUrl    https://gitee.com/chuzifeng/script-cat-script/raw/master/%E6%8B%BC%E5%A4%9A%E5%A4%9A%E6%94%B6%E8%97%8F%E5%A4%B9%E9%87%87%E9%9B%86.js
// ==/UserScript==

(function() {
    'use strict';
    
    const 资源路径 = 'https://mobile.yangkeduo.com/proxy/api/api/zenon/merge_pay_list/';
    let allData = []; // 存储所有采集的数据
    let countDisplay, filteredCountDisplay, keywordInput;
    let panel, toggleButton;
    let isMonitoring = false;

    // 创建UI面板
    function createUIPanel() {
        panel = document.createElement("div");
        panel.style.position = "fixed";
        panel.style.top = "10px";
        panel.style.left = "10px";
        panel.style.zIndex = "9999";
        panel.style.background = "rgba(0, 0, 0, 0.8)";
        panel.style.color = "white";
        panel.style.padding = "20px";
        panel.style.borderRadius = "10px";
        panel.style.width = "300px";
        panel.style.display = "flex";
        panel.style.flexDirection = "column";
        panel.style.gap = "15px";
        panel.style.boxShadow = "0 0 10px rgba(0, 0, 0, 0.3)";

        // 添加收起/展开按钮
        const toggleButton = document.createElement("button");
        toggleButton.style.position = "absolute";
        toggleButton.style.right = "-30px";
        toggleButton.style.top = "0";
        toggleButton.style.width = "20px";
        toggleButton.style.height = "20px";
        toggleButton.style.cursor = "pointer";
        toggleButton.style.border = "none";
        toggleButton.style.borderRadius = "50%";
        toggleButton.style.background = "#333";
        toggleButton.style.color = "white";
        toggleButton.innerHTML = "←";
        toggleButton.onclick = () => {
            if (panel.style.transform === "translateX(-100%)") {
                panel.style.transform = "translateX(0)";
                toggleButton.innerHTML = "←";
            } else {
                panel.style.transform = "translateX(-100%)";
                toggleButton.innerHTML = "→";
            }
        };
        panel.appendChild(toggleButton);

        // 标题样式优化
        const title = document.createElement("h2");
        title.innerText = "拼多多收藏夹采集器";
        title.style.textAlign = "center";
        title.style.margin = "0 0 15px 0";
        title.style.fontSize = "18px";
        title.style.fontWeight = "bold";
        title.style.borderBottom = "1px solid rgba(255,255,255,0.2)";
        title.style.paddingBottom = "10px";
        panel.appendChild(title);

        // 数据统计显示样式优化
        countDisplay = document.createElement("div");
        countDisplay.innerText = "已采集数据：0 条";
        countDisplay.style.textAlign = "center";
        countDisplay.style.padding = "10px";
        countDisplay.style.background = "rgba(255,255,255,0.1)";
        countDisplay.style.borderRadius = "5px";
        panel.appendChild(countDisplay);

        // 关键词筛选输入框样式优化
        keywordInput = document.createElement("input");
        keywordInput.type = "text";
        keywordInput.placeholder = "输入关键词筛选";
        keywordInput.style.padding = "8px 12px";
        keywordInput.style.border = "none";
        keywordInput.style.borderRadius = "5px";
        keywordInput.style.width = "100%";
        keywordInput.style.boxSizing = "border-box";
        keywordInput.style.background = "rgba(255,255,255,0.9)";
        panel.appendChild(keywordInput);

        // 按钮容器
        const buttonContainer = document.createElement("div");
        buttonContainer.style.display = "flex";
        buttonContainer.style.gap = "10px";
        buttonContainer.style.marginTop = "10px";

        // 开始采集按钮样式优化
        const startButton = document.createElement("button");
        startButton.innerText = "开始采集";
        startButton.style.flex = "1";
        startButton.style.padding = "8px";
        startButton.style.border = "none";
        startButton.style.borderRadius = "5px";
        startButton.style.background = "#4CAF50";
        startButton.style.color = "white";
        startButton.style.cursor = "pointer";
        startButton.onclick = async () => {
            if (!isMonitoring) {
                updateButtonStatus(startButton, true);
                await startCollection();
            }
        };
        buttonContainer.appendChild(startButton);

        // 导出Excel按钮样式优化
        const exportButton = document.createElement("button");
        exportButton.innerText = "导出Excel";
        exportButton.style.flex = "1";
        exportButton.style.padding = "8px";
        exportButton.style.border = "none";
        exportButton.style.borderRadius = "5px";
        exportButton.style.background = "#2196F3";
        exportButton.style.color = "white";
        exportButton.style.cursor = "pointer";
        exportButton.onclick = () => downloadExcel(allData);
        buttonContainer.appendChild(exportButton);

        panel.appendChild(buttonContainer);

        // 添加过渡效果
        panel.style.transition = "transform 0.3s ease-in-out";
        
        // 添加到页面
        document.body.appendChild(panel);
    }

    // 修改开始采集流程
    async function startCollection() {
        console.log('开始采集数据');
        isMonitoring = true;
        
        // 采集当前页面数据
        if (unsafeWindow.rawData) {
            console.log('获取到页面数据');
            const firstPageData = 提取商品信息(unsafeWindow.rawData);
            if (firstPageData && firstPageData.length > 0) {
                updateData(firstPageData);
                console.log('页面数据采集完成:', firstPageData.length, '条');
            } else {
                console.log('页面数据提取为空');
            }
        }
        
        // 监听资源路径数据
        const originalSend = XMLHttpRequest.prototype.send;
        XMLHttpRequest.prototype.send = function(body) {
            const xhr = this;
            const originalOnReadyStateChange = xhr.onreadystatechange;
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    const url = xhr.responseURL;
                    if (url && url.includes(资源路径)) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            console.log('获取到资源路径数据');
                            const pageData = 提取后续页面信息(response);
                            if (pageData && pageData.length > 0) {
                                updateData(pageData);
                                console.log('资源路径数据采集完成:', pageData.length, '条');
                            }
                        } catch (error) {
                            console.error('解析资源路径数据失败:', error);
                        }
                    }
                }
                if (originalOnReadyStateChange) {
                    originalOnReadyStateChange.apply(this, arguments);
                }
            };
            
            return originalSend.apply(this, arguments);
        };
    }

    // 更新数据和UI显示
    function updateData(newData) {
        if (newData && newData.length) {
            allData = [...allData, ...newData];
            // 更新数据计数
            countDisplay.innerText = `已采集数据：${allData.length} 条`;
            // 添加动画效果
            countDisplay.style.animation = 'pulse 0.5s';
            setTimeout(() => {
                countDisplay.style.animation = '';
            }, 500);
        }
    }

    // 下载Excel文件
    function downloadExcel(data) {
        if (data.length === 0) {
            alert("没有数据可以导出！");
            return;
        }

        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(data.map(item => ({
            "商品名称": item[0],
            "店铺名称": item[1],
            "商品链接": item[2],
            "商品ID": item[3],
            "价格": item[4],
            "销量": item[5]
        })));

        XLSX.utils.book_append_sheet(wb, ws, "商品数据");
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        
        const blob = new Blob([wbout], { type: 'application/octet-stream' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `拼多多收藏夹商品_${new Date().toLocaleDateString()}.xlsx`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }

    // 保持原有的数据提取函数
    function 提取商品信息(rawData) {
        const 所有商品信息 = [];

        // 确保 baseStore.goodsSet 存在
        if (rawData && rawData.baseStore && rawData.baseStore.goodsSet) {
            // 遍历 goodsSet 中的每个商品
            for (let 商品Id in rawData.baseStore.goodsSet) {
                const 商品 = rawData.baseStore.goodsSet[商品Id];
                
                // 提取商品相关信息
                const 商品信息 = [
                    商品.goodsName,  // 商品名称
                    商品.mallName,   // 店铺名称
                    'https://mobile.yangkeduo.com/' + 商品.goodsPageUrl, // 商品链接
                    商品.goodsId,    // 商品ID
                    商品.mergePayList ? 商品.mergePayList[0].skuPrice / 100 : null, // 价格（除以100转换为元）
                    商品.salesTip // 销量
                ];

                // 将提取到的信息添加到结果数组
                所有商品信息.push(商品信息);
            }
        } else {
            console.log("没有找到 goodsSet 数据");
        }

        return 所有商品信息;
    }

    function 提取后续页面信息(data) {
        const 后续商品信息 = [];

        // 确保 goods_list 存在
        if (data && data.goods_list) {
            // 遍历 goods_list 中的每个商品
            for (let 商品 of data.goods_list) {
                // 提取商品相关信息
                const 商品信息 = [
                    商品.base_goods_info.goods_name,  // 商品名称
                    商品.mall_info.mall_name,   // 店铺名称
                    'https://mobile.yangkeduo.com/' + 商品.base_goods_info.link_url, // 商品链接
                    商品.base_goods_info.goods_id,    // 商品ID
                    商品.total_price / 100, // 价格（除以100转换为元）
                    商品.base_goods_info.sales_tip // 销量
                ];

                // 将提取到的信息添加到结果数组
                后续商品信息.push(商品信息);
            }
        } else {
            console.log("没有找到 goods_list 数据");
        }

        return 后续商品信息;
    }

    // 添加CSS动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .collecting {
            animation: collecting 1s infinite;
        }
        
        @keyframes collecting {
            0% { opacity: 1; }
            50% { opacity: 0.6; }
            100% { opacity: 1; }
        }
    `;
    document.head.appendChild(style);

    // 优化按钮状态
    function updateButtonStatus(startButton, isCollecting) {
        if (isCollecting) {
            startButton.innerText = "采集中...";
            startButton.style.background = "#f44336";
            startButton.classList.add('collecting');
        } else {
            startButton.innerText = "开始采集";
            startButton.style.background = "#4CAF50";
            startButton.classList.remove('collecting');
        }
    }

    // 移除页面加载时的自动检查
    window.addEventListener('load', async () => {
        createUIPanel();
        console.log('面板创建完成');
    });
})();

